const jsonWebToken = require("jsonwebtoken")
const userModel = require("../models/userModel")
const {SECRET_KEY} = require("../utils/config")
const listToTree = require("../utils/toTree")

module.exports = {
  async login(req, res) {
    try {
      const loginResult = await userModel.login(req.body.username, req.body.password)

      console.log("登陆成功：", loginResult)

      if (loginResult.length === 0) {
        // 账号或者密码错误
        return res.json({
          errCode: "1001",
          errMsg: "fail",
        })
      }

      // 查询用户部门
      const branchResult = await userModel.getBranch(loginResult[0].branch_id)
      console.log("用户部门:", branchResult)

      // 查询用户角色
      const roleResult = await userModel.getRole(loginResult[0].user_id)
      console.log("用户角色:", roleResult)

      // 查询用户权限
      const permissionResult = await userModel.getPermission(roleResult[0].roleId)
      console.log("用户权限:", permissionResult)

      // 扁平数组转树状
      const permissionTree = listToTree(permissionResult)
      console.log("权限转树状结果:", permissionTree)

      // 生成 token
      const token = jsonWebToken.sign(
        {
          username: req.body.username,
        },
        SECRET_KEY,
        {
          algorithm: "HS256", // algorithm:"HS256"  默认使用 "HS256" 算法
          expiresIn: "24h", // token 有效期
        }
      )

      res.json({
        errCode: "200",
        errMsg: "ok",
        data: {
          userId: loginResult[0].user_id,
          username: req.body.username,
          ...branchResult[0],
          ...roleResult[0],
          token,
          permissionResult,
        },
      })
    } catch (err) {
      console.log("登录错误：", err)
      res.json({
        errCode: "1001",
        errMsg: "fail",
        err,
      })
    }
  },
  register(req, res) {},
}
